package com.lap.watchdog.starter.autoconfigure;

import com.lap.watchdog.starter.aspect.RepeatSubmitAspect;
import com.lap.watchdog.starter.core.CaffeineRepeat;
import com.lap.watchdog.starter.core.RedisRepeat;
import com.lap.watchdog.starter.core.Repeat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.StringRedisTemplate;

@Slf4j
@AutoConfiguration
public class WatchdogAutoConfiguration {

  /**
   * 重复提交AOP
   *
   * @param repeat 注解
   * @return 重复提交拦截器
   */
  @Bean
  RepeatSubmitAspect repeatAspect(Repeat repeat) {
    log.info("Initializer watchdog repeat aspect");
    return new RepeatSubmitAspect(repeat);
  }

  /**
   * 防重提交(优先级高)
   *
   * @param redisTemplate 缓存操作对象
   * @return 防重对象
   */
  @Bean
  @Primary
  @ConditionalOnClass(StringRedisTemplate.class)
  Repeat redisRepeat(StringRedisTemplate redisTemplate) {
    log.info("Initializer watchdog redis cache, redisTemplate:{}", redisTemplate);
    return new RedisRepeat(redisTemplate);
  }

  /**
   * 防重提交（兜底策略）
   *
   * @return 防重对象
   */
  @Bean
  @ConditionalOnMissingBean(Repeat.class)
  Repeat caffeineRepeat() {
    log.info("Initializer watchdog local cache");
    return new CaffeineRepeat();
  }
}
